package com.gxa.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gxa.common.LayR;
import com.gxa.common.R;
import com.gxa.mapper.EmplMapper;
import com.gxa.mapper.EmplRoleMapper;
import com.gxa.param.TableParam;
import com.gxa.pojo.Empl;
import com.gxa.pojo.EmplRole;
import com.gxa.service.EmplService;
import com.gxa.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.List;

@Service
@Transactional(rollbackFor = Throwable.class)
public class EmplServiceImpl implements EmplService {

    @Autowired
    private EmplMapper mapper;

    @Autowired
    private EmplRoleMapper emplRoleMapper;


    /**
     * 获取员工列表
     * @param param
     * @return
     */
    @Override
    public LayR list(TableParam param) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<Empl> empls = mapper.findAll(param);
        // 封装pageInfo
        PageInfo<Empl> pageInfo = new PageInfo<>(empls);
        List<Empl> list = pageInfo.getList();
        for (Empl empl : list) {
            System.out.println(empl);
        }

        return new LayR(0, "success", pageInfo.getTotal(), pageInfo.getList());
    }


    /**
     * 改变状态的方法
     * @param empl
     * @return
     */
    @Override
    public LayR changeStatus(Empl empl) {
        mapper.update(empl);
        return new LayR(200, "success");
    }


    /**
     * 添加员工
     * @param empl ： 员工对象
     * @param roleIds ： 角色ID
     * @return
     */
    @Override
    public R add(Empl empl, String[] roleIds) {

        // 先添加员工
        // 处理密码
        empl.setEmplPwd(MD5Util.MD55(empl.getEmplPwd()));
        // 创建时间
        empl.setCreateTime(new Timestamp(System.currentTimeMillis()));
        mapper.save(empl);

        // 再添加关系表
        for (String roleId : roleIds) {
            // 组装关系表对象
            EmplRole emplRole = new EmplRole(empl.getId(), Integer.valueOf(roleId));
            // 添加
            emplRoleMapper.save(emplRole);
        }

        return new R(200, "添加成功！");
    }

    /**
     * 逻辑删除
     * @param ids
     * @return
     */
    @Override
    public R deleteAll(String[] ids) {
        mapper.deleteAll(ids);
        return new R(200, "删除成功！");
    }

    /**
     * 员工的详情
     * @param id
     * @return
     */
    @Override
    public R detail(Integer id) {
        Empl empl = mapper.findByPk(id);
        return new R(200, "success", empl);
    }
}
